const CryptoJS = require('crypto-js') // 引用AES源码js
// AES加密 必须要16位 加密秘钥  这里的key 和 iv 必须和服务器端一致
const _key = CryptoJS.enc.Utf8.parse('ALMWORKHOURIOCSJ') // 十六位十六进制数作为密钥
const _iv = CryptoJS.enc.Utf8.parse('IOWORKHOUR202003') // 十六位十六进制数作为密钥偏移量

/**
 * @param {string} word
 * @returns {string}
 * 默认的加密方法
 */
export function encrypt (word) {
  var _word = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(_word, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * @param {string} word
 * @returns {string}
 * 根据结果获取的iv动态加密字符串
 */
export function ivEncrypt (iv, word) {
  var _word = CryptoJS.enc.Utf8.parse(word)
  // var _word = CryptoJS.enc.Hex.parse(word);
  // var _key = CryptoJS.enc.Utf8.parse(key)
  // var _iv = CryptoJS.enc.Utf8.parse(iv)
  var encrypted = CryptoJS.AES.encrypt(_word, _key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * @param {string} word
 * @returns {string}
 * 解密方法
 */
function hexDecrypt (word) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(word)
  const src = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const decrypt = CryptoJS.AES.decrypt(src, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

/**
 * @param {string} word
 * @returns {string}
 * 另一种hex加密方法
 */
function hexEncrypt (word) {
  const src = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(src, _key, {
    iv: _iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.ciphertext.toString().toUpperCase()
}

export default {
  encrypt,
  hexEncrypt,
  hexDecrypt,
  ivEncrypt
}
